package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EsManagerServiceImpl implements EsManagerService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ESManagerMapper esManagerMapper;

    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importDataToESBySpuId(String spuId) {
        //根据spuid查询相关sku列表
        List<Sku> skuList = skuFeign.findListBySpuId(spuId);
        if (skuList == null || skuList.size()<=0){
            throw new RuntimeException("当前商品无数据,无法导入索引库:   "+spuId);
        }
        //将数据转换成json
        String jsonSkuList = JSON.toJSONString(skuList);
        //将json转换为索引库对象
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuList, SkuInfo.class);

        //遍历
        for (SkuInfo skuInfo : skuInfoList) {
            //将规格json转换为map
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void delSkuListBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findListBySpuId(spuId);
        if (skuList == null || skuList.size()<=0){
            throw new RuntimeException("当前商品无数据,无法导入索引库:   "+spuId);
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }

    @Override
    public void importAll() {
        List<Sku> skuList = skuFeign.findListBySpuId("all");
        if (skuList == null || skuList.size()<=0){
            throw new RuntimeException("当前商品数据不存在");
        }
        //将skulist转换为json
        String skuJsonList = JSON.toJSONString(skuList);
        //将json转换为索引库对象
        List<SkuInfo> skuInfoList = JSON.parseArray(skuJsonList, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfoList) {
            //将规格转换为map
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfoList);
    }
}
